﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace HYSoft.Web
{
    public partial class m_node : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["uid"] == null || Session["uid"] == "")
            {
                Context.Response.Write("<script language=\"javascript\" type=\"text/javascript\">");
                Context.Response.Write("alert('对不起,你登录时间超时,请重新登录');top.location.href=\"index.html\";");
                Context.Response.Write("</script>");
                Context.Response.End();
            }
            if (Request.QueryString["tomonitor"] == null)
                no_node();
            else
            {
                if (!IsPostBack)
                {
                    m_node_list();
                    monitor_list();
                    monitor2user();
                    clritem();
                }
                nodetype_change();
            }
        }
        /// <summary>
        /// 根据用户序列号绑定该序列号下的所有监测点
        /// </summary>
        private void m_node_list()
        {
            string sql = " [user_index]=" + int.Parse(Session["uid"].ToString()) + "";
            DataSet ds = new BLL.usr2monitor().GetList(sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                DropDownList1.DataSource = ds.Tables[0].DefaultView;
                DropDownList1.DataTextField = "addr";
                DropDownList1.DataValueField = "index";
                DropDownList1.DataBind();
                ds.Clear();
                ds.Dispose();
                DropDownList1.SelectedValue = Request.QueryString["tomonitor"].ToString();
            }
        }
        /// <summary>
        /// 待分配传感器节点的绑定，areano=-1表示没有被分配的传感器节点
        /// </summary>
        private void monitor_list()
        {
            string sql = " [areano]=-1";
            DataSet ds = new BLL.gprsNode().GetList(sql);
            ListItem[] items = new ListItem[ds.Tables[0].Rows.Count];
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                ListItem item = new ListItem();
                item.Value = ds.Tables[0].Rows[i]["Index"].ToString();
                item.Text = ds.Tables[0].Rows[i]["Addr"].ToString() + " (" + ds.Tables[0].Rows[i]["mac"].ToString() + "  " + GetMName(int.Parse(ds.Tables[0].Rows[i]["adminno"].ToString())) + ")";
                items[i] = item;
            }
            lstAll.Items.AddRange(items);
            ds.Clear();
            ds.Dispose();
        }
        /// <summary>
        /// 通过传感器编号得到传感器的名称
        /// </summary>
        /// <param name="adminno"></param>
        /// <returns></returns>
        private string GetMName(int adminno)
        {
            string sql = " adminno=" + adminno + "";
            DataSet ds = new BLL.sensor_node().GetList(sql);
            return ds.Tables[0].Rows[0]["name"].ToString();
        }
        /// <summary>
        /// 如果该单位不存在监测点则提示，有则重新加载这个页面，并将相应的值传入
        /// </summary>
        private void no_node()
        {
            string sql = " [user_index]=" + int.Parse(Session["uid"].ToString()) + "";
            DataSet ds = new BLL.usr2monitor().GetList(sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                Response.Write("<script>window.location = 'm_node.aspx?tomonitor=" + ds.Tables[0].Rows[0]["index"] + "';</script>");
            }
            else
            {
                Response.Write("<script>alert('该单位还没有已创建的监测点！');history.back();</script>");
            }
        }
        /// <summary>
        /// 将已分配给该单位的传感器绑定到已分配的listbox中，通过传递过来的areano查询
        /// </summary>
        private void monitor2user()
        {
            string sql = " [areano]=" + Request.QueryString["tomonitor"].ToString() + "";
            DataSet ds = new BLL.gprsNode().GetList(sql);
            lstSelected.DataSource = ds.Tables[0].DefaultView;
            lstSelected.DataTextField = "Addr";//指定下拉列表中的文字显示部分 
            lstSelected.DataValueField = "Index";//指定下拉列表中的值部分 
            lstSelected.DataBind();
            ds.Clear();
            ds.Dispose();
        }
        /// <summary>
        /// 如果某传感器节点已经移到lstSelect中，则将该节点从lstAll里面删除
        /// </summary>
        private void clritem()
        {
            foreach (ListItem item in lstSelected.Items)
            {
                if (lstAll.Items.Contains(item))//判断lstAll里面是的某个传感器节点否存在lstSelect中
                {
                    int index = this.lstAll.Items.IndexOf(item);
                    this.lstAll.Items.RemoveAt(index);
                }
            }
        }
        /// <summary>
        /// 监测点改变则更新到该监测点所管束的传感器
        /// </summary>
        protected void nodetype_change()
        {
            string nodetype = DropDownList1.SelectedValue.ToString();
            if (nodetype != Request.QueryString["tomonitor"].ToString())
                Response.Write("<script>window.location = 'm_node.aspx?tomonitor=" + nodetype + "';</script>");
        }
        /// <summary>
        /// 将某传感器分配到该监测点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btAddOne_Click(object sender, EventArgs e)
        {
            int index = lstAll.Items.Count;
            for (int i = 0; i < index; i++)
            {
                if (lstAll.SelectedIndex == i)
                {
                    lstSelected.Items.Add(lstAll.SelectedItem);
                    lstAll.Items.RemoveAt(i);
                }
            }
        }
        /// <summary>
        /// 删除该监测点下的某个传感器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelOne_Click(object sender, EventArgs e)
        {
            int index = lstSelected.Items.Count;
            for (int i = 0; i < index; i++)
            {
                if (lstSelected.SelectedIndex == i)
                {
                    lstAll.Items.Add(lstSelected.SelectedItem);
                    lstSelected.Items.RemoveAt(i);
                }
            }
        }
        /// <summary>
        /// 将所有未分配的传感器全部分配给该监测点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddAll_Click(object sender, EventArgs e)
        {
            int i = 0;
            foreach (ListItem item in lstAll.Items)
            {
                lstSelected.Items.Insert(i, item);
                i = i + 1;
            }
            lstAll.Items.Clear();
        }
        /// <summary>
        /// 删除该监测点下的所有传感器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelAll_Click(object sender, EventArgs e)
        {
            int i = 0;
            foreach (ListItem item in lstSelected.Items)
            {
                lstAll.Items.Insert(i, item);
                i = i + 1;
            }
            lstSelected.Items.Clear();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string sql = " [areano]=" + DropDownList1.SelectedValue.ToString() + "";
            DataSet ds = new BLL.gprsNode().GetList(sql);
            foreach (ListItem item in lstSelected.Items)
            {
                int flag1 = 0;
                //判断该监测点下的传感器是否数据中都已经存在，如果有一个不存在就更新
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (item.Value == ds.Tables[0].Rows[i]["index"].ToString())
                        flag1 = 1;
                }
                if (flag1 == 0)
                {
                    Model.gprsNode grn = new BLL.gprsNode().GetModel(int.Parse(item.Value));
                    grn.areano = int.Parse(DropDownList1.SelectedValue.ToString());
                    new BLL.gprsNode().Update(grn);
                }
            }
            //如果数据库中的某个传感器被移除，则更新
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                int flag2 = 0;
                foreach (ListItem item in lstSelected.Items)
                {
                    if (ds.Tables[0].Rows[i]["index"].ToString() == item.Value)
                        flag2 = 1;
                }
                if (flag2 == 0)
                {
                    Model.gprsNode grn = new BLL.gprsNode().GetModel(int.Parse(ds.Tables[0].Rows[i]["index"].ToString()));
                    grn.areano = -1;
                    new BLL.gprsNode().Update(grn);
                }
            }

            Response.Write("<script>alert('更新成功');window.location = 'm_node.aspx?tomonitor=" + DropDownList1.SelectedValue.ToString() + "';</script>");
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Write("<script>window.location = 'm_node.aspx?tomonitor=" + DropDownList1.SelectedValue.ToString() + "';</script>");
        }

        protected void lstSelected_SelectedIndexChanged(object sender, EventArgs e)
        {
            lstAll.SelectedIndex = -1;
        }
        protected void lstAll_SelectedIndexChanged(object sender, EventArgs e)
        {
            lstSelected.SelectedIndex = -1;
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            Response.Write("<script>window.location = 'equipment_add66.aspx?adminnos=66';</script>");
        }
        protected void Button3_Click(object sender, EventArgs e)
        {
            if (lstAll.SelectedIndex == -1)
            {
                Response.Write("<script>alert('请先在\"待分配传感器节点\"列表中选中要删除的传感器节点，然后才点击\"删除\"按钮进行传感器节点删除！');history.back();</script>");
            }
            else
            {
                int gid = int.Parse(lstAll.SelectedValue);
                string macold = "";
                string sql = " [index]=" + gid + "";
                DataSet ds = new BLL.gprsNode().GetList(sql);
                Model.mac_value macvalue = new BLL.mac_value().GetModel(int.Parse(ds.Tables[0].Rows[0]["mac"].ToString()));
                macvalue.level2 = 0;
                new BLL.mac_value().Update(macvalue);
                macold = ds.Tables[0].Rows[0]["mac"].ToString();

                sql = " [mac]=" + ds.Tables[0].Rows[0]["mac"] + "";
                DataSet nodeuser = new BLL.node_to_user().GetList(sql);
                new BLL.node_to_user().Delete(int.Parse(nodeuser.Tables[0].Rows[0]["index"].ToString()));

                DataSet gprsnodelog = new BLL.gprsNodeLog().GetList(sql);
                new BLL.gprsNodeLog().Delete(int.Parse(gprsnodelog.Tables[0].Rows[0]["index"].ToString()));

                new BLL.gprsNode().Delete(gid);
                ds.Clear();
                ds.Dispose();
                nodeuser.Clear();
                nodeuser.Dispose();
                gprsnodelog.Clear();
                gprsnodelog.Dispose();

                Response.Write("<script>alert('删除传感器节点成功！mac值" + macold + "已回收！');window.location = 'm_node.aspx';</script>");
            }

        }
    }
}